package com.yjht.online.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONTokener;
import com.yjht.online.generate.impl.person.plat.kd.PersonGenerateProssorKd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Path;

public class OnLineFileUtil {

    final static Logger logger = LoggerFactory.getLogger(PersonGenerateProssorKd.class);

    public static boolean isJar() {

        String protocol = OnLineFileUtil.class.getResource("").getProtocol();
        System.out.println(protocol);
        if ("jar".equals(protocol)) {
            System.out.println("jar 加载");
            //jar包加载
            return true;
        } else {
            //本地加载
            return false;
        }
    }



    public static InputStream getInputStream(String path) {
        path = getRuningFilePath(path);
        System.out.println(path);
        return FileUtil.getInputStream(path);
    }
    public static String getRuningFilePath(String path){

        if(isJar()){
            System.out.println("jar 加载");
            String jarPath = getJarPath();
            return FileUtil.normalize(jarPath + StrUtil.SLASH  + path);
        }
        return FileUtil.normalize(FileUtil.getAbsolutePath("./") + path) ;

    }

    public static File getOutPutFile(String fileName){
        return FileUtil.file(getOutPutPath(fileName)) ;
    }
    public static String getOutPutPath(String fileName){
        if(isJar()){
            return getRuningFilePath(fileName);
        }
        String runPath = getRuningFilePath("");
        String lastPath = FileUtil.getParent(runPath,1);
        return FileUtil.normalize(lastPath + StrUtil.SLASH + fileName);
    }

    /**
     * 获取项目加载类的根路径
     * @return
     */
    public static String getJarPath(){
        String path = "";
        try{
            //jar 中没有目录的概念
            URL location = OnLineFileUtil.class.getProtectionDomain().getCodeSource().getLocation();//获得当前的URL
            File file = new File(location.getPath());//构建指向当前URL的文件描述符
            if(file.isDirectory()){//如果是目录,指向的是包所在路径，而不是文件所在路径
                path = file.getAbsolutePath();//直接返回绝对路径
            }else{//如果是文件,这个文件指定的是jar所在的路径(注意如果是作为依赖包，这个路径是jvm启动加载的jar文件名)
                path = file.getParent();//返回jar所在的父路径
            }
            logger.info("project path={}",path);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("{}",e);
        }
        return path;
    }
}
